package cn.glc.daily.life.config.shiro.filter;

import cn.glc.daily.life.common.constans.Constant;
import cn.glc.daily.life.common.enums.GlobalCodeEnum;
import cn.glc.daily.life.common.exceptions.GlobalException;
import cn.glc.daily.life.common.utils.JsonResult;
import cn.glc.daily.life.config.shiro.token.JwtToken;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

import static cn.glc.daily.life.common.enums.GlobalCodeEnum.BusinessExceptionEnum.TOKEN_EXPIRE_ERROR;
import static cn.glc.daily.life.common.enums.GlobalCodeEnum.BusinessExceptionEnum.UNAUTHORIZED_ERROR;
import static cn.glc.daily.life.common.enums.GlobalCodeEnum.SystemExceptionEnum.SYSTEM_EXCEPTION;


/**
 * @author simon
 * @date 2020/9/20 16:41
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String authorization = ((HttpServletRequest) request).getHeader(Constant.TOKEN_HEADER_NAME);
        return authorization != null;
    }

    /**
     * 执行登录认证
     *
     * @param request     ServletRequest
     * @param response    ServletResponse
     * @param mappedValue mappedValue
     * @return 是否成功
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (isLoginAttempt(request, response)) {
            return executeLogin(request, response);
        } else {
            responseError(request, response, UNAUTHORIZED_ERROR);
        }
        return false;
    }

    /**
     * 执行登录
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(Constant.TOKEN_HEADER_NAME);
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 过滤器的所有异常都转到controller中的异常方法做统一处理
     *
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        try {
            super.doFilterInternal(request, response, chain);
        } catch (UnauthorizedException e) {
            resolveException(e);
        } catch (Exception e) {
            request.setAttribute("exceptionErrorMsg", resolveException(e));
            request.getRequestDispatcher("/error/throw").forward(request, response);
        }
    }

    private GlobalException resolveException(Throwable e) {
        while (e.getCause() != null) {
            e = e.getCause();
            resolveException(e);
        }
        GlobalException globalException = null;
        if (e instanceof TokenExpiredException) {
            globalException = new GlobalException(TOKEN_EXPIRE_ERROR);
        } else if (e instanceof AuthenticationException) {
            globalException = new GlobalException(UNAUTHORIZED_ERROR);
        } else if (e instanceof Exception) {
            globalException = new GlobalException(SYSTEM_EXCEPTION);
        }
        return globalException;
    }

    private void responseError(ServletRequest request, ServletResponse response, GlobalCodeEnum.BusinessExceptionEnum unauthorizedError) {
        Writer out = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8);
            response.setContentType("application/json; charset=utf-8");
            out = new BufferedWriter(outputStreamWriter);
            out.write(JSONObject.toJSONString(JsonResult.returnFailure(unauthorizedError)));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStreamWriter) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
